package com.laker.autotest.testcase;

import com.jayway.jsonpath.JsonPath;
import com.laker.autotest.core.BasePageTest;
import com.laker.autotest.page.csdn.CsdnSearchPage;
import com.microsoft.playwright.Response;
import lombok.extern.slf4j.Slf4j;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * 模拟开发中用浏览器进行API和页面测试
 */
@Slf4j
public class CsdnApiAndPageTest extends BasePageTest {
    @Test
    public void 从搜索页测试搜索() {
        CsdnSearchPage searchPage = new CsdnSearchPage(page);
        searchPage.clickUserTab();
        searchPage.search("lakernote");
        // 模拟API测试
        //  拦截/监控所有的请求和响应
        page.onRequest(request -> log.info(">> " + request.method() + " " + request.url()));
        page.onResponse(response -> {
            log.info("<<" + response.status() + " " + response.url());
            if (response.request().url().contains("/search")) {
                log.info("<<" + response.text());
            }
        });

        // 监听websocket
        // 监听websocket的连接
        page.onWebSocket(ws -> {
            log.info("WebSocket opened: " + ws.url());
            ws.onFrameSent(frameData -> log.info(frameData.text()));
            ws.onFrameReceived(frameData -> log.info(frameData.text()));
            ws.onSocketError(error -> log.error(error));
            ws.onClose(ws1 -> log.info("WebSocket closed"));
        });
        // 模拟页面测试
        String searchResult = searchPage.getSearchResult();
        Assert.assertTrue(searchResult.contains("lakernote"));


        // 模拟API测试 单击按钮后等待网络响应
        Response response = page.waitForResponse(r -> r.url().contains("/search"), () -> {
            page.locator("#search").click();
        });
        log.info("response: " + response.text());
        Assert.assertTrue(response.ok());
        // https://jsonpath.com/
        // https://jsonpathfinder.com/
        Assert.assertTrue(JsonPath.read(response.text(), "$.result_vos[0].nickname").toString().contains("lakernote"));

    }
}
